<template>
  <div class="app-container">
    <avue-crud
      ref="crud"
      :option="option"
      :data="data"
      :table-loading="loading"
      :page.sync="page"
      @on-load="onLoad"
      @current-change="currentChange"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="resetChange"
      :search.sync="searchList"
    >
      <!-- <template slot="search" slot-scope="{row,size}">
        <div class="el-col el-col-10 el-col-offset-0 el-col-xs-24 el-col-sm-12 el-col-md-10 avue-form__row" style="padding-left: 10px; padding-right: 10px;">
          <div class="el-form-item el-form-item--small avue-form__item--">
            <label for="daterange" class="el-form-item__label" style="width: 130px;">日期范围:</label>
            <div class="el-form-item__content" style="margin-left: 130px;">
              <el-date-picker v-model="searchList.createTime" type="daterange" :size="size" range-separator="至" start-placeholder="开始日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" end-placeholder="结束日期">
              </el-date-picker>
            </div>
          </div>
        </div>
      </template> -->
      <template
        slot="icon"
        slot-scope="scope"
      >
        <div v-if="scope.row.icon">
          <svg-icon :icon-class="scope.row.icon"></svg-icon>
        </div>
      </template>
      <template slot="menuLeft">
        <div style="display:inline-block;">
          <div style="display:flex">
            <el-button
              type="primary"
              size="small"
              @click="add"
              icon="el-icon-plus"
              v-has="'blackAdd'"
            > 新 增</el-button>
          </div>
        </div>
      </template>
      <template
        slot="menu"
        slot-scope="scope"
      >
        <el-button
          size="small"
          type="text"
          @click="checkOpen(scope.row,scope.index)"
          icon="el-icon-edit"
        >编辑</el-button>
        <el-button
          size="small"
          type="text"
          @click="rowDel(scope.row)"
          icon="el-icon-delete"
        >删除</el-button>
      </template>
    </avue-crud>

    <el-dialog
      :title="dialogTitle"
      class="avue-dialog"
      :visible.sync="dialogVisble"
      width="60%"
      center
    >
      <el-form
        :model="formData"
        ref="payForm"
        label-width="120px"
      >
        <el-form-item
          label="政策标题"
          prop="title"
          :rules="[{ required: true, message: '请输入政策标题', trigger: 'blur' }]"
        >
          <el-input v-model="formData.title"></el-input>
        </el-form-item>
        <el-form-item
          label="上传封面"
          prop="pictureUrl"
          :rules="[{ required: true, message: '请上传封面', trigger: 'blur' }]"
        >
          <el-upload
            class="avatar-uploader"
            :headers="headers"
            :action="uploadUrl"
            :show-file-list="false"
            :with-credentials="true"
            :on-success="handleAvatarSuccess"
            :on-remove="handleRemove"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="formData.pictureUrl"
              :src="formData.pictureUrl"
              class="avatar"
            >
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
            ></i>
            <div
              class="el-upload__tip"
              v-if="!formData.pictureUrl"
              slot="tip"
            >上传jpg/png文件,大小不能超过2MB</div>
          </el-upload>
          <!-- <el-upload
                        class="myUpload"
                        action="#"
                        list-type="picture"
                        :on-change="beforeAvatarUpload"
                        :limit="1"
                        :file-list="formData.fileList"
                        :auto-upload="false">
                            <i v-if="!formData.fileList.length" style="font-size:14px" class="el-icon-plus avatar-uploader-icon">
                            上传封面图片</i>
                            <div slot="file" slot-scope="{file}">
                            <img
                                class="el-upload-list__item-thumbnail"
                                :src="file.url" alt=""
                            >
                            </div>
                            <div class="el-upload__tip" v-if="!formData.fileList.length" slot="tip">上传jpg/png文件,大小不能超过2MB</div>
                        </el-upload> -->
        </el-form-item>
        <el-form-item
          label="编辑内容"
          prop="editorContent"
          :rules="[{ required: true, message: '请输入内容', trigger: 'blur' }]"
        >
          <editor
            :content="formData.editorContent"
            min-height="100"
            @change="updateData"
          ></editor>
        </el-form-item>
        <el-form-item
          label="信息来源"
          prop="infoFrom"
          :rules="[{ required: true, message: '请输入信息来源', trigger: 'blur' }]"
        >
          <el-input v-model="formData.infoFrom"></el-input>
        </el-form-item>
        <el-form-item
          label="政策排序"
          prop="sortNum"
          :rules="[{ required: true, message: '请输入政策排序', trigger: 'blur' }]"
        >
          <el-input
            type="number"
            v-model="formData.sortNum"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer">
        <el-button
          type="primary"
          v-if="dialogType === 'add'"
          @click="addSave"
          round
        >保存</el-button>
        <el-button
          type="primary"
          v-if="dialogType === 'edit'"
          @click="editSave"
          round
        >保存</el-button>
        <el-button
          @click="dialogVisble = false"
          type="primary"
          plain
          round
        >取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addJrzc,
  selJrzc,
  updJrzc,
  showRzcp,
  delJrzc,
  getFile,
} from '@/api/manager.js'
import { editorOotion } from './finance.util'
import { mapGetters } from 'vuex'
import VueHtml5Editor from 'vue-html5-editor'
import { json } from 'body-parser'
const editor = new VueHtml5Editor(editorOotion)
export default {
  components: {
    editor,
  },
  data() {
    return {
      loading: false,
      /* 分页 */
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
        background: false,
      },
      data: [],
      option: {
        headerAlign: 'center',
        align: 'center',
        border: true,
        index: true,
        indexLabel: '序号',
        indexWidth: 100,
        card: true,
        defaultExpandAll: true,
        dialogDrag: false,
        labelWidth: 135,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        excelBtn: false,
        selection: false,
        searchLabelWidth: '20%',
        searchSpan: 8,
        searchMenuSpan: 4,
        columnBtn: false,
        refreshBtn: false,
        selectClearBtn: false,
        // searchBtn: true,
        searchShowBtn: false,
        addBtn: false,
        column: [
          {
            label: '政策标题',
            prop: 'title',
            display: false,
            search: true,
          },
          {
            label: '日期范围',
            prop: 'daterange',
            search: true,
            hide: true,
            searchRange: true,
            type: 'daterange',
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
          },
          {
            label: '信息来源',
            prop: 'infoFrom',
            display: false,
          },
          // {
          //     label: '政策发布时间',
          //     prop: 'createTime',
          //     display: false,
          //     search: true,
          //     searchRange:true,
          //     type: "daterange",
          //     format:'yyyy-MM-dd',
          //     valueFormat:'yyyy-MM-dd',
          // }
          {
            label: '政策发布时间',
            prop: 'createTime',
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
          },
        ],
      },
      searchList: {},
      formData: {
        title: '',
        mainBody: '',
        pictureUrl: '',
        infoFrom: '',
        editorContent: '',
        _pictureUrl: '',
        sortNum: '',
        //fileList:[],

        // fileList:[{
        //     url:'https://map-mobile-resource.cdn.bcebos.com/icon/service/pc-station/default/truck_pay.jpg'
        // }],
      },
      dialogVisble: false,
      dialogType: 'add',
      dialogTitle: '新增',

      headers: '',
    }
  },
  created() {
    this.headers = { TOKEN: this.token }
    this.uploadUrl = process.env.VUE_APP_BASE_API + '/finasm/jrzc/updateFile'
  },
  computed: {
    ...mapGetters(['token']),
  },
  filters: {},
  methods: {
    onLoad() {
      const { daterange } = this.searchList
      const params = {
        ...this.searchList,
        startTime: daterange ? daterange[0] : '',
        endTime: daterange ? daterange[1] : '',
        pageNum: this.page.currentPage,
        pageSize: this.page.pageSize,
      }
      this.loading = true
      selJrzc(params).then((data) => {
        if (data.status) {
          this.data = data.data.records
          this.page.total = data.data.total
        } else {
          this.$message({
            type: 'error',
            message: data.msg,
          })
        }
        this.loading = false
      })
    },
    /* 清空 */
    resetChange() {
      this.page.currentPage = 1
      this.page.pageSize = 10
      this.onLoad()
    },
    /* 搜索筛选 */
    searchChange(params, done) {
      done()
      this.page.currentPage = 1
      this.page.pageSize = 10
      this.onLoad()
    },
    /* 新增 */
    addSave() {
      console.log('addSave', this.formData)
      const { _pictureUrl, infoFrom, editorContent, title, sortNum } =
        this.formData
      this.$refs['payForm'].validate((valid) => {
        if (valid) {
          addJrzc({
            pictureUrl: _pictureUrl,
            infoFrom,
            title,
            mainBody: this.escapeHTMLTwo(editorContent),
            sortNum,
          }).then((res) => {
            if (res.status) {
              this.openCel = false
              this.$message({
                type: 'success',
                message: '操作成功!',
              })
              this.onLoad(this.page)
            } else {
              this.$message({
                type: 'error',
                message: res.msg,
              })
            }
            this.dialogVisble = false
          })
        }
      })

      // addRzcp(row).then((data) => {
      //     if (data.status) {
      //         this.$message({
      //             type: "success",
      //             message: "操作成功!"
      //         });
      //         this.onLoad(this.page);
      //     }
      //     done();
      // }, error => {
      //     window.console.log(error);
      //     loading();
      // });
    },
    /* 编辑 */
    checkOpen(row, type) {
      console.log(row)
      console.log(row.mainBody)
      const { infoFrom, mainBody, pictureUrl, title, sortNum } = row
      let params = { filePath: pictureUrl }
      getFile(params).then((res) => {
        this.formData.pictureUrl = res.data
      })
      this.formData = {
        infoFrom,
        pictureUrl,
        _pictureUrl: null,
        title,
        editorContent: this.escapeHTMLThree(mainBody),
        // editorContent: '上世纪九十年代一位来自运城的押司姓宋名江江湖人称及时雨宋公明,被迫上梁山. 一会回你   飒飒<div>户数</div><div><br></div><div><br></div><div>撒啊</div>',
        sortNum,
      }
      this.dialogType = 'edit'
      this.dialogTitle = '查看'
      this.currentRow = row
      this.dialogVisble = true
    },
    //查看
    handleAvatarSuccess(res, file) {
      console.log('handleAvatarSuccess', res, file)
      this.formData._pictureUrl = res.data
      this.formData.pictureUrl = URL.createObjectURL(file.raw)
    },
    /* 修改 */
    editSave() {
      const { id } = this.currentRow
      const { _pictureUrl, infoFrom, editorContent, title, sortNum } =
        this.formData
      this.$refs['payForm'].validate((valid) => {
        if (valid) {
          updJrzc({
            pictureUrl: _pictureUrl,
            infoFrom,
            title,
            id,
            mainBody: this.escapeHTMLTwo(editorContent),
            sortNum,
          }).then((res) => {
            if (res.status) {
              this.openCel = false
              this.$message({
                type: 'success',
                message: '操作成功!',
              })
              this.onLoad(this.page)
            } else {
              this.$message({
                type: 'error',
                message: res.msg,
              })
            }
            this.dialogVisble = false
          })
        }
      })
    },
    add() {
      this.dialogType = 'add'
      this.dialogTitle = '新增'
      this.formData = {
        title: '',
        mainBody: '',
        pictureUrl: '',
        infoFrom: '',
        editorContent: '',
        _pictureUrl: '',
      }

      this.dialogVisble = true
      // this.$nextTick(() => {
      //     console.log(this.$refs['payForm']);
      //     this.$refs['payForm'].resetFields()
      // })
    },
    /* 改变页码 */
    currentChange(currentPage) {
      this.page.currentPage = currentPage
    },
    /* 删除 */
    rowDel(row) {
      this.$confirm('是否删除该条政策?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.loading = true
        delJrzc({ id: row.id }).then(
          (res) => {
            if (res.status) {
              this.$message({
                type: 'success',
                message: res.msg,
              })
              this.onLoad(this.page)
            } else {
              this.$message({
                type: 'error',
                message: res.msg,
              })
            }
            this.loading = false
          },
          (error) => {
            window.console.log(error)
          }
        )
      })
    },

    beforeAvatarUpload(file, fileList) {
      console.log('beforeAvatarUpload', file, fileList)
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传片大小不能超过 2MB!')
        return isLt2M
      }
    },
    updateData(da) {
      console.log(da)
      this.formData.editorContent = da
    },
    escapeHTMLTwo(str) {
      if (str) {
        // str = str.replace(/<div>/g, "&ga");
        // str = str.replace(/<\/div>/g, "&gb");
        // str = str.replace(/<br>/g, "&gc");
        // str = str.replace(/nbsp;/g, "&gd");
        str = str.replace(/</g, '&ga')
        str = str.replace(/>/g, '&gb')
      }
      console.log(str)
      return str
    },
    escapeHTMLThree(str) {
      if (str) {
        // str = str.replace(/&ga/g, "<div>");
        // str = str.replace(/&gb/g, "</div>");
        // str = str.replace(/&gc/g, "<br>");
        // str = str.replace(/&gd/g, "nbsp;");
        str = str.replace(/&ga/g, '<')
        str = str.replace(/&gb/g, '>')
      }
      console.log(str)
      return str
    },

    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
  },
}
</script>

<style scoped="scoped" lang="scss">
/deep/ .avue-crud__pagination {
  text-align: center;
}
.dialog-footer {
  text-align: center;
  margin: 20px auto;
}
.avue-dialog {
  /deep/ .myUpload {
    //width: 300px;
    // height: 300px;
    // .el-upload-list--picture{
    //     width: 200px !important;
    //     height: 300px !important;
    //     .is-success,.is-ready{
    //         height: 300px !important;
    //     }
    //     .el-upload-list__item-thumbnail{
    //         height: 300px !important;
    //     }
    // }
    // .avatar-uploader-icon {
    //     font-size: 28px;
    //     color: #8c939d;
    //     width: 178px;
    //     height: 178px;
    //     line-height: 178px;
    //     text-align: center;
    //     border: 1px solid #ccc;
    // }
  }
  /deep/ .avatar-uploader .el-upload {
    border: 1px dashed #666;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
